package com.auth.leaves.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * springboot全局处理Long类到前端精度丢失问题
 *
 * 由于Java中Long类型为18位，而JS中只有16位，所以前端JS使用Java后端传过来的Long/long会丢失精度，后端将返回的数据改为String使用即可
 * @Author LEAVES
 * @Date 2020/9/4
 * @Version 1.0
 */
//@EnableWebMvc
@Configuration
@Slf4j
public class WebDataConvertConfig implements WebMvcConfigurer {

    //上传的文件存储地址
    @Value("${upload.local.path}")
    private String localPath;


    /**
     *添加消息转化类
     * @param list
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> list) {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jsonConverter.getObjectMapper();
        //序列换成json时,将所有的long变成string
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        list.add(jsonConverter);
    }

    /**
     * 上传文件配置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        /**
         *  /source/xxx   指文件的访问方式  如：localhost:8080/source/abc.wav
         *  file:d/voice/  指静态文件存放在服务器上的位置
         */
        log.info("上传的文件存储地址=====> " + localPath);
        registry.addResourceHandler("/**").addResourceLocations("file:" + localPath);
    }
}
